package basic.thread.again;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author bingo
 * @create 2018-03-01 9:49
 **/
public class ReadWriteLockDemo {

    private Map<String,Object> map = new HashMap<>();

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private Lock read = readWriteLock.readLock();

    private Lock write = readWriteLock.writeLock();


    public Object getObject(String key){
        System.out.println(Thread.currentThread().getName()+"读操作执行");
        read.lock();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            return map.get(key);
       }finally {
            read.unlock();
            System.out.println(Thread.currentThread().getName()+"读操作执行完毕");
        }
    }

    public void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写操作执行");
        write.lock();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            map.put(key,value);
        }finally {
            write.unlock();
            System.out.println(Thread.currentThread().getName()+"写操作执行完毕");
        }

    }

    public static void main(String[] args) {

        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                   readWriteLockDemo.put("k1","v1");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.put("k2","v2");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.put("k3","v3");
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.getObject("k1");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.getObject("k2");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                readWriteLockDemo.getObject("k3");
            }
        }).start();


    }
}
